//
//  FPCertificateViewController.m
//  ForestPack
//
//  Created by jimmy on 2018/7/4.
//  Copyright © 2018年 郑洲. All rights reserved.

///  进入人认证的界面

#import "FPCertificateViewController.h"
#import "UIView+Utils.h"
#import "FPReviewViewController.h"
#import "FPSelectRoleViewController.h"
#import <AFNetworking.h>

//#import "PhotoAlertView.h"


@interface FPCertificateViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

@property (nonatomic,strong)  UILabel      * textLabel;
@property (nonatomic,strong)  UIImageView  * progressView;
@property (nonatomic,strong)  UIButton     * submitButton;
@property (nonatomic,strong)  UIImageView  * leftImageView ;
@property (nonatomic,strong)  UIImageView  * rightImageView ;
@property (nonatomic, assign) BOOL           isLeft;

@property (nonatomic,copy)  NSString  * leftImageUrl;
@property (nonatomic,copy)  NSString  * rightImageUrl;

@property (nonatomic,strong)  NSMutableArray  * leftImageArray;
@property (nonatomic,strong)  NSMutableArray  * rightImageArray;

@end

@implementation FPCertificateViewController

- (NSMutableArray *)leftImageArray
{
    if (_leftImageArray == nil) {
        _leftImageArray = [[NSMutableArray alloc] init];
    }
    return _leftImageArray;
}

- (NSMutableArray *)rightImageArray
{
    if (_rightImageArray == nil) {
        _rightImageArray = [[NSMutableArray alloc] init];
    }
    return _rightImageArray;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setPersonCertificateViewUI];
}

#pragma mark - 设置上传身份证正反面的点击事件（调相机或相册）
-(void)leftTapClick
{
    _isLeft = YES;
    [self alterIconPortrait];
}

-(void)rightTapClick
{
    _isLeft = NO;
    [self alterIconPortrait];
}

#pragma mark----- 选择弹出框
-(void)alterIconPortrait
{
    //弹出提示框
    __weak typeof(self)weakSelf = self;
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：拍摄
    [alert addAction:[UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf openCamare];
    }]];
    //按钮：从手机相册选择
    [alert addAction:[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        [weakSelf openAlbum];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 打开相册
-(void)openAlbum
{
    //    UIImagePickerControllerSourceTypePhotoLibrary,         所有相册
    //    UIImagePickerControllerSourceTypeCamera,               相机
    //    UIImagePickerControllerSourceTypeSavedPhotosAlbum，    moment中
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - 打开相机
-(void)openCamare
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

    //选择显示的图片
    if (_isLeft) {
        [self.leftImageArray addObject:image];
        self.leftImageView.image = image;
    }else{
        [self.rightImageArray addObject:image];
        self.rightImageView.image = image;
        
    }
    //关闭选择界面
    [picker dismissViewControllerAnimated:YES completion:nil];

}

-(void)backClick
{
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - 提交认证
-(void)submitClick
{
    [self uploadImage];
}

- (void)uploadImage
{
    if (self.leftImageArray.count <= 0 || self.rightImageArray <= 0) {
        return;
    }
    
    [HttpManager uploadImageArr:self.leftImageArray success:^(id successResponse) {
        
        self.leftImageUrl = successResponse[0];//[NSString stringWithFormat:@"%@",successResponse[0]];
        
        [HttpManager uploadImageArr:self.rightImageArray success:^(id successResponse) {
            
            self.rightImageUrl = successResponse[0];//[NSString stringWithFormat:@"%@",successResponse[0]];
            [self submitCertifyInfo];
        }];
    }];
}

-(void)submitCertifyInfo
{
    UITextField *nameTextF = [self.view viewWithTag:1001];
    UITextField *numTextF = [self.view viewWithTag:1002];
    
    if (nameTextF.text.length <= 0 || numTextF.text.length <= 0) {
        [HttpManager showNoteMsg:@"请填写完整"];
        return;
    }
    if (self.leftImageUrl.length <= 0 || self.rightImageUrl.length <= 0) {
        [HttpManager showNoteMsg:@"请上传身份证信息"];
        return;
    }
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    [dict setValue:self.phoneStr forKey:@"mobile"];
    [dict setValue:nameTextF.text forKey:@"realname"];
    [dict setValue:self.password forKey:@"password"];
    [dict setValue:numTextF.text forKey:@"card_id"];
    [dict setValue:self.leftImageUrl forKey:@"pic1"];
    [dict setValue:self.rightImageUrl forKey:@"pic2"];
    [dict setValue:kNSUDefaultReadKey(@"longitude") forKey:@"longitude"];
    [dict setValue:kNSUDefaultReadKey(@"latitude") forKey:@"latitude"];
    
    NSString *url = [NSString stringWithFormat:@"%@app/app_personal_register",REQUESTHEADER];//个人用户注册
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            kNSUDefaultSaveVauleAndKey(successResponse[@"token"], @"token");
            kNSUDefaultSaveVauleAndKey(self.phoneStr, @"phone");
            
            FPReviewViewController *reviewVC = [[FPReviewViewController alloc] init];
            [self.navigationController pushViewController:reviewVC animated:true];
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

-(void)setPersonCertificateViewUI
{
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(13, APP_STATUSBAR_HEIGHT, 22, 22)];
    [leftButton setImage:[UIImage imageNamed:@"返回红色"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftButton];
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.centerX = self.view.centerX;
    topImageView.size = CGSizeMake(80, 80);
    topImageView.left = (SCREEN_WIDTH - 80) / 2;
    topImageView.top =  NAVIGATION_BAR_HEIGHT + 10;
    topImageView.image = [UIImage imageNamed:@"组11"];
    [self.view addSubview:topImageView];
    
    self.textLabel = [[UILabel alloc] init];
    self.textLabel.frame = CGRectMake((SCREEN_WIDTH - 150)/2, topImageView.bottom + 10, 150, 20);
    self.textLabel.font = [UIFont systemFontOfSize:18];
    self.textLabel.textColor = RGB_COLOR(51, 51, 51);
    self.textLabel.text = @"实名认证";
    self.textLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.textLabel];
    
    self.progressView = [[UIImageView alloc] init];
    self.progressView.frame = CGRectMake(30, self.textLabel.bottom + 30, SCREEN_WIDTH - 60, 26);
    self.progressView.contentMode = UIViewContentModeCenter;
    self.progressView.image = [UIImage imageNamed:@"完成"];
    [self.view addSubview:self.progressView];
    
    [self setCenterViewUI];
    
    self.submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.submitButton.backgroundColor = RGB_COLOR(237, 34, 59);
    self.submitButton.frame = CGRectMake(40, SCREEN_HEIGHT - 105, SCREEN_WIDTH - 80, 44);
    self.submitButton.layer.masksToBounds = true;
    self.submitButton.layer.cornerRadius = 22;
    [self.submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [self.submitButton addTarget:self action:@selector(submitClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.submitButton];
    
    
}

-(void)setCenterViewUI
{
    UIView *centerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.progressView.bottom+30, SCREEN_WIDTH, 223)];
    [self.view addSubview:centerView];
    
    UIImageView *nameIamge = [[UIImageView alloc] initWithFrame:CGRectMake(40, 31, 20, 21)];
    nameIamge.image = [UIImage imageNamed:@"姓名"];
    [centerView addSubview:nameIamge];
    
    UITextField *nameTextF = [[UITextField alloc] initWithFrame:CGRectMake(nameIamge.right+10, 31, SCREEN_WIDTH - 100, 20)];
    nameTextF.placeholder = @"请输入您的姓名";
    nameTextF.tag = 1001;
    nameTextF.clearButtonMode =  UITextFieldViewModeWhileEditing;
    [centerView addSubview:nameTextF];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(40, nameTextF.bottom + 15, SCREEN_WIDTH - 80, 1)];
    line1.backgroundColor = RGBACOLOR(238, 238, 238, 1);
    [centerView addSubview:line1];
    
    UIImageView *numIamge = [[UIImageView alloc] initWithFrame:CGRectMake(40, line1.bottom + 31, 20, 21)];
    numIamge.image = [UIImage imageNamed:@"身份证号"];
    [centerView addSubview:numIamge];
    
    UITextField *numTextF = [[UITextField alloc] initWithFrame:CGRectMake(nameIamge.right+10, line1.bottom + 31, SCREEN_WIDTH - 100, 20)];
    numTextF.placeholder = @"请输入您的身份证号";
    numTextF.tag = 1002;
    numTextF.clearButtonMode =  UITextFieldViewModeWhileEditing;
    [centerView addSubview:numTextF];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(40, numTextF.bottom + 15, SCREEN_WIDTH - 80, 1)];
    line2.backgroundColor = RGBACOLOR(238, 238, 238, 1);
    [centerView addSubview:line2];
    
    self.leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, line2.bottom + 16, 140, 95)];
    self.leftImageView.tag = 1003;
    self.leftImageView.userInteractionEnabled = YES;
    self.leftImageView.image = [UIImage imageNamed:@"身份证正面"];
    //给UIImageView添加一个点击事件
    UIButton *tapBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 140, 95)];
    tapBtn.backgroundColor = [UIColor clearColor];
    [tapBtn addTarget:self action:@selector(leftTapClick) forControlEvents:UIControlEventTouchUpInside];
    [self.leftImageView addSubview:tapBtn];
    [centerView addSubview:self.leftImageView];
    
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, self.leftImageView.bottom + 5, 140, 12)];
    leftLabel.text = @"上传身份证正面";
    leftLabel.textAlignment = NSTextAlignmentCenter;
    leftLabel.textColor = RGB_COLOR(153, 153, 153);
    leftLabel.font = [UIFont systemFontOfSize:12];
    [centerView addSubview:leftLabel];
    self.rightImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 40 - 140, line2.bottom + 16, 140, 95)];
    self.rightImageView.tag = 1004;
    self.rightImageView.userInteractionEnabled = YES;
    self.rightImageView.image = [UIImage imageNamed:@"身份证反面"];
    //给UIImageView添加一个点击事件
    UIButton *tapBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 140, 95)];
    tapBtn1.backgroundColor = [UIColor clearColor];
    [tapBtn1 addTarget:self action:@selector(rightTapClick) forControlEvents:UIControlEventTouchUpInside];
    [self.rightImageView addSubview:tapBtn1];
    [centerView addSubview:self.rightImageView];
    
    
    UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 40 - 140, self.leftImageView.bottom + 5, 140, 12)];
    rightLabel.text = @"上传身份证反面";
    rightLabel.textAlignment = NSTextAlignmentCenter;
    rightLabel.textColor = RGB_COLOR(153, 153, 153);
    rightLabel.font = [UIFont systemFontOfSize:12];
    [centerView addSubview:rightLabel];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:true];
}

/*
 - (void)uploadImage:(UIImage *)img
 {
 NSData *imageData = [NSData data];
 if (img) {
 imageData = UIImageJPEGRepresentation(img, kUploadImageCompressionRatio);
 }
 
 NSString *urlStr = [NSString stringWithFormat:@"%@/app/ajax_file_upload",REQUESTHEADER];
 
 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
 
 [manager POST:urlStr parameters:@{@"files[]":imageData} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
 [formData appendPartWithFileData:imageData name:@"files[]" fileName:@"shopHead.jpg" mimeType:@"image/jpeg"];
 } progress:^(NSProgress * _Nonnull uploadProgress) {
 
 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
 if ([responseObject[@"status"] integerValue] == 1) {
 [HttpManager hideWait];
 NSString *picUrl = [NSString stringWithFormat:@"%@",responseObject[@"pic"][0]];
 
 if (self.isLeft) {
 // 上传成功
 self.leftImageUrl = picUrl;
 }else{
 self.rightImageUrl = picUrl;
 }
 
 }else{
 [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
 }
 
 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
 
 [HttpManager showNoteMsg:@"上传失败"];
 }];
 
 }
 
 - (void)submitEnterprise
 {
 // 点击按钮 先定位  拿到定位信息之后 在进行下面操作
 
 UITextField *nameTextF = [self.view viewWithTag:1001];
 UITextField *numTextF = [self.view viewWithTag:1002];
 
 if (nameTextF.text.length <= 0 || numTextF.text.length <= 0) {
 [HttpManager showNoteMsg:@"请填写完整"];
 return;
 }
 if (self.leftImageUrl.length <= 0 || self.rightImageUrl.length <= 0) {
 [HttpManager showNoteMsg:@"请上传身份证信息"];
 return;
 }
 
 NSMutableDictionary * dict = [NSMutableDictionary dictionary];
 [dict setValue:self.phoneStr forKey:@"mobile"];
 [dict setValue:nameTextF.text forKey:@"realname"];
 [dict setValue:self.password forKey:@"password"];
 [dict setValue:numTextF.text forKey:@"card_id"];
 
 [dict setValue:self.enterpriseImageUrl forKey:@"营业执照"]; // 营业执照
 
 [dict setValue:@(self.finalRegisterType) forKey:@"customer_type"];
 
 [dict setValue:@"" forKey:@"longitude"];
 [dict setValue:@"" forKey:@"latitude"];
 
 // 必须要 但是 接口没有
 [dict setValue:self.leftImageUrl forKey:@"pic1"];
 [dict setValue:self.rightImageUrl forKey:@"pic2"];
 [dict setValue:self.enterpriseNameStr forKey:@"公司名称"];
 
 
 NSString *url = [NSString stringWithFormat:@"%@app/app_company_register",REQUESTHEADER];//企业用户注册
 [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
 NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
 if ([status isEqualToString:@"1"]) {
 kNSUDefaultSaveVauleAndKey(successResponse[@"token"], @"token");
 
 FPReviewViewController *reviewVC = [[FPReviewViewController alloc] init];
 [self.navigationController pushViewController:reviewVC animated:true];
 }else{
 [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
 }
 } andFailure:^(id failureResponse) {
 [HttpManager showFail];
 }];
 }
 */

@end

